<template>
  <el-dialog
    :visible.sync="visible"
    :width="width"
    top="13vh"
    :before-close="closeDialogHandle"
    :close-on-click-modal="false">
    <div slot="title">
      <span class="el-dialog__title">{{ role.roleName }}</span>
      <span class="simple-name">({{ role.roleKey }})</span>
      <span class="el-dialog__title">{{ title }}</span>
    </div>
    <el-button v-if="optType" :disabled="buttonLoad || userSelection.length === 0"
               @click="unassociatedUserHandle(undefined)"
               type="danger" size="mini" plain icon="el-icon-delete" class="mb7">
      批量解除
    </el-button>
    <el-table
      v-loading="dataLoad"
      element-loading-text="用户数据加载中..."
      element-loading-spinner="el-icon-loading"
      max-height="500"
      :data="showUserList"
      @selection-change="val => this.userSelection = val"
      ref="userTable"
      >
      <el-table-column v-if="optType" type="selection" header-align="center" align="center" width="50">
      </el-table-column>
      <el-table-column type="index" header-align="center" align="center" label="序号" width="50"></el-table-column>
      <el-table-column header-align="center" align="center" label="用户名称">
        <template v-slot="{ row }">
          <div>
            <span>{{ row.username }}</span>
            <span>（{{ row | loginIdFormat }}）</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" header-align="center" align="center" label="关联时间" width="135">
      </el-table-column>
      <el-table-column prop="createUser" header-align="center" align="center" label="操作用户" width="135">
      </el-table-column>
      <el-table-column
        v-if="optType"
        align="left"
        width="200">
        <template slot="header">
          <el-input :disabled="userList.length === 0" v-model="searchText" @input="searchUserHandle" size="mini"
                    placeholder="输入用户名称搜索" />
        </template>
        <template v-slot="{ row }">
          <el-button type="text" icon="el-icon-delete" @click="unassociatedUserHandle(row)">解除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <span slot="footer">
      <el-button @click="closeDialogHandle">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    name: "dept-user-view-dialog",
    data() {
      return {
        // 弹出框显示状态[true-显示 false-隐藏]
        visible: false,
        // 弹出框标题
        title: undefined,
        // 弹出框宽度
        width: undefined,
        // 操作类型[true-操作 false-查看]
        optType: undefined,
        // 角色对象
        role: {
          // 角色主键
          roleId: undefined,
          // 角色名称
          roleName: undefined,
          // 角色键
          roleKey: undefined,
        },
        // 用户列表
        userList: [],
        // 表格显示的用户列表
        showUserList: [],
        // 选择用户列表
        userSelection: [],
        // 用户检索内容
        searchText: '',
        // 用户检索定时器
        searchTimer: undefined,
        // 数据加载状态[true-加载 false-不加载]
        dataLoad: false,
        // 按钮状态[false-可以被点击 true-不可被点击]
        buttonLoad: false,
      }
    },
    filters: {
      /**
       * 用户登录信息映射
       * @param {Object} value 用户对象
       */
      loginIdFormat(value) {
        if (value.loginName) {
          return value.loginName;
        }
        if (value.phone) {
          return value.phone;
        }
        if (value.email) {
          return value.email;
        }
        return '未知'
      }
    },
    methods: {
      init(role, optType) {
        // 打开弹出框
        this.visible = true;
        this.title = '角色已关联用户';
        this.width = optType ? '55%' : '40%';
        this.optType = optType;

        let _role = this.role;
        for (let propKey in _role) {
          if (role.hasOwnProperty(propKey)) {
            _role[propKey] = role[propKey];
          }
        }

        this.getUserList();
      },
      /**
       * 获取用户列表方法
       * 根据部门主键是否为空，请求角色已关联或可关联的用户数据
       */
      getUserList() {
        // 开始数据加载
        this.dataLoad = true;
        let url = '/sys/user-role/relation/user/list';
        let params = {
          roleId: this.role.roleId
        }
        this.$axios.$get(url, { params: params })
          .then(({ data }) => {
            this.userList = data;
            this.showUserList = data;
          })
          .catch(() => {})
          .finally(() => {
            // 数据加载结束
            this.dataLoad = false;
          })
      },
      /**
       * 用户搜索事件
       * @param value 最新搜索值
       */
      searchUserHandle(value) {
        clearTimeout(this.searchTimer);
        this.searchTimer = setTimeout(() => {
          // 用户过滤
          this.showUserList = this.userList.filter(user => !value || user.username.includes(value));
          clearTimeout(this.searchTimer);
        }, 300);
      },
      /**
       * 用户解除关联角色事件
       * @param {Object} user 用户对象
       */
      unassociatedUserHandle(user) {
        // 按钮禁用
        this.buttonLoad = true;
        let message, relationIdList;
        if (user) {
          message = `‘${user.username}’用户解除关联‘${this.role.roleName}’角色成功`;
          relationIdList = [user.relationId];
        } else {
          message = `用户批量解除关联‘${this.role.roleName}’角色成功`
          relationIdList = this.userSelection.map(_user => _user.relationId);
        }
        this.$axios.$delete('/sys/user-role/unassociated', { data: relationIdList })
          .then(() => {
            this.notify('success', '操作成功', message)
            // 重新加载用户列表
            this.getUserList();
          })
          .catch(() => {})
          .finally(() => {
            // 按钮恢复可点击
            this.buttonLoad = false;
          })
      },
      /**
       * 关闭弹出框事件
       */
      closeDialogHandle() {
        // 关闭弹出框
        this.visible = false;
        this.title = undefined;
        this.width = undefined;
        this.optType = undefined;
        let role = this.role;
        for (let propKey in role) {
          role[propKey] = undefined;
        }
        this.userList = [];
        this.showUserList = [];
        this.userSelection = [];
        this.searchText = '';
        this.searchTimer = undefined;
      }
    }
  }
</script>

<style scoped>
  /deep/ .el-dialog__body {
    padding: 20px;
  }
  .simple-name {
    color: #909399;
  }
  .mb7 {
    margin-bottom: 7px;
  }
</style>
